/**
 * 
 */

$(function() {
    var templateData = refreshTemplate("");
	builderTh(templateData);

	$("#getSelected")
			.on(
					"click",
					function() {
						var checkResult = checkAndSaveTmp();
						if (checkResult.checkType) {
							checkResult.action = "addTemplate";
							var result = ajaxToServer("refreshData",
									checkResult);
							if (result.saveType) {
								// 从新加载页面
								window.location.href = "http://"+getSystemPath()+"/jumpDemo";
							} else {
								alert("新增失败");
							}
						}

					});
});
/**
 * 和后台服务同步
 * 
 * @param action
 *            server映射
 * @param data
 *            请求的数据
 */
var ajaxToServer = function(action, data) {
	var returnValue = "";
	var path = $('#path').val();
	$.ajax({
		url : path + "/" + action,
		type : "POST",
		dataType : "json",
		data : data,
		async : false,
		success : function(retVal) {
			returnValue = retVal;
		},
		error : function() {
			alert("错误，请联系管理员！");
		}
	});
	return returnValue;
};

/**
 * 检查查询模板是否符合规则 return true： 符合 false：不符合
 */
var checkAndSaveTmp = function() {
	$('.pop_error').remove();
	var checkResult = {};
	var templateName = $('#tmp_in').val().replace(/(^\s*)|(\s*$)/g, '');
	var option = $("#option").val();
	var opRow = 0;
	if (templateName == "") {
		// error
		$('#cp_os_ul').append('<li class="pop_error">请填写模板名称！</li>');
		return false;
	}
	if (option == "add")
		opRow = 0;
	else
		opRow = $("#opRow").val();

	
	var newNameIsExist = isExistVal(opRow,templateName);
	if(newNameIsExist){
		$('#cp_os_ul').append('<li class="pop_error">已存在此名称！</li>');
		return false;
	}
	var entities = [];
	$("#pickListResult option").each(function() {
		var text = $(this).text();
		entities.push(text);
	});
	if (entities.length == 0) {
		// 没有选择查询泪
		checkResult.checkType = false;
		$('#cp_os_ul').append('<li class="pop_error">请选择要查询的类！</li>');
	}
	if (checkResult.checkType == undefined)
		checkResult.checkType = true;
	checkResult.entities = entities.join(',');
	checkResult.templateName = templateName;
	return checkResult;
};


/**
 * 创建table头
 * 
 * @returns
 */
var builderTh = function(templateData) {
	$("#templateData").empty();
	builderTop(0, templateData, 'block');
};
/**
 * 构建模型展示树
 * 
 * @param count
 *            右移像素
 * @param dataJSon
 *            json数据
 * @param dis
 *            初始化显隐性
 * @param viewType
 *            模型视图类型
 * @returns
 */
var builderTop = function(count, templateData) {
	var table = $("#templateData");
	table.find('tr').remove();
	tr = '<tr><th class="gx_col" style="text-align: center;" scope="col"  >模板名称</th><th class="gx_enCol" scope="col">创建者</th><th class="gx_enCol" scope="col">修改人</th><th class="gx_color" scope="col">修改时间</th><th class="gx_wide" scope="col">说明</th><th class="gx_opr" style="text-align: center;" scope="col">操作</th> </tr>';
	table.append(tr);
	if (templateData.length < 0) {
		return;
	}
	$
			.each(
					templateData,
					function(n, template) {
						var tr = $('<tr>');
						var queryTmpName = template.queryTmpName;
						var creatUser = template.creatUser;
						var updator = template.updator;
						var lastUpdateDate = template.lastUpdateDate;
						var note = template.note;
						var firTd = $('<td>');
						var hiddenIn1 = $('<input type ="hidden" id="'
								+ queryTmpName + '" value="' + queryTmpName
								+ '"/>');
						firTd.append(hiddenIn1);
						var div1 = $('<div class="tbdiv" style="padding-left:0em;"><span class="spanl fuxuan"><input type="checkbox" /></span> <span class="spanl tbimg"><img src="'+$('#path').val()+'/css/images/mag20_5.png" /></span> <span class="spanl tbname">'
								+ queryTmpName
								+ '</span><span class="spanl"><a class="tbedit" href="javascript:void(0)" onclick="updateName(this,\'template\');event.cancelBubble=true;"></a></span> <span class="spanr"><s class="tbdown"></s></span></div>');
						firTd.append(div1)
						tr
								.append(firTd)
								.append(
										'<td>'
												+ creatUser
												+ '</td><td>'
												+ updator
												+ '</td><td>'
												+ lastUpdateDate
												+ '</td><td>'
												+ note
												+ '</td><td  class="tda"><a href="javascript:void(0)" onclick="add_or_update_template(this)">修改</a><a href="javascript:void(0)" onclick="deleteData(this)">删除</a></td>');
						// tr.hide();
						table.append(tr);
						div1.bind("click", function() {
							openOrCloseMenu(this);
						});
						var entitis = template.nodes;
						$
								.each(
										entitis,
										function(m, entity) {
											var secoTr = $('<tr>');
											var entityName = entity.entityName;
											var secoTd = $('<td>');
											var hiddenIn2 = $('<input type ="hidden" id="'
													+ queryTmpName
													+ "."
													+ entityName
													+ '" value="'
													+ queryTmpName
													+ "."
													+ entityName + '"/>');
											secoTd.append(hiddenIn2);
											var div2 = $('<div class="tbdiv" style="padding-left:1em;"><span class="spanl fuxuan"><input type="checkbox" /></span> <span class="spanl tbimg"><img src="'+$('#path').val()+'/css/images/icon16_pail.png" /></span> <span class="spanl tbname">'
													+ entityName
													+ '</span><span class="spanl" style="display:none"><a class="tbedit" href="javascript:void(0)"></a></span> <span class="spanr"><s class="tbdown"></s></span></div>');
											secoTd.append(div2);
											secoTr.append(secoTd);
											secoTr
													.append('<td></td><td></td><td></td><td></td><td class="tda"><a href="javascript:void(0)"  onclick="addAlia(this)">添加</a><a href="javascript:void(0)" onclick="deleteData(this)">删除</a></td>');
											secoTr.hide();
											table.append(secoTr);
											div2.bind("click", function() {
												openOrCloseMenu(this);
											});

											var alias = entity.nodes;
											$
													.each(
															alias,
															function(h, alia) {
																var aliaName = alia.aliaName;
																var aliaTr = $('<tr>');
																var div3 = $('<div class="tbdiv" style="padding-left:2em;">');
																div3
																		.append('<span class="spanl fuxuan"><input type="checkbox" /></span> <span class="spanl tbimg"><img src="'+$('#path').val()+'/css/images/icon16_edit.png" /></span> <span class="spanl tbname">'
																				+ aliaName
																				+ '</span><span class="spanl"><a class="tbedit" onclick="updateName(this,\'alia\');event.cancelBubble=true;" href="javascript:void(0)"></a></span> <span class="spanr"><s class="tbdown"></s></span>');
																var td3 = $('<td>');
																var hiddenIn3 = $('<input type ="hidden" id="'
																		+ queryTmpName
																		+ "."
																		+ entityName
																		+ "."
																		+ aliaName
																		+ '" value="'
																		+ queryTmpName
																		+ "."
																		+ entityName
																		+ "."
																		+ aliaName
																		+ '"/>');
																td3
																		.append(hiddenIn3);

																td3
																		.append(div3);
																aliaTr
																		.append(
																				td3)
																		.append(
																				'<td></td><td></td><td></td><td></td><td  class="tda"><a href="javascript:void(0)" onclick="editAlia(this)">编辑</a><a href="javascript:void(0)" onclick="deleteData(this)">删除</a></td>');
																aliaTr.hide();
																table
																		.append(aliaTr);
																div3
																		.bind(
																				"click",
																				function() {
																					openOrCloseMenu(this);
																				});
																var temp = alia.properties;
																if (temp.length > 0)
																	var properties = temp
																			.split(',');
																for (k in properties) {
																	var forth = $('<tr>');
																	forth
																			.append('<td><input type ="hidden" id="'
																					+ queryTmpName
																					+ "."
																					+ entityName
																					+ "."
																					+ aliaName
																					+ "."
																					+ properties[k]
																					+ '" value="'
																					+ queryTmpName
																					+ "."
																					+ entityName
																					+ "."
																					+ aliaName
																					+ "."
																					+ properties[k]
																					+ '"/><div class="tbdiv" style="padding-left:3em;"><span class="spanl fuxuan"><input type="checkbox" /></span> <span class="spanl tbimg"><img src="'+getSystemPath+'/css/images/icon16_trans.png" /></span> <span class="spanl tbname">'
																					+ properties[k]
																					+ '</span><span class="spanl" style="display:none"><a class="tbedit" href="javascript:void(0)"></a></span> <span class="spanr" style="display:none"><s class="tbdown"></s></span></div></td><td></td><td></td><td></td><td></td><td  class="tda"><a href="javascript:void(0)" onclick="deleteData(this)">删除</a></td>');
																	forth
																			.hide();
																	table
																			.append(forth);
																}

															});
										});
					});
};

/**
 * 根据类名获取类的节点
 * 
 * @param className
 */
var findDataByClsName = function(className) {
	var currentDate;
	var table = $('#leftTable');
	$('table tr').each(
			function(i, evTr) {
				try {
					var currentVal = $(evTr).find(">td input[type='hidden']")
							.val();
					var d = currentVal.length - className.length - 1;
					if ((d > 0 && currentVal.lastIndexOf('.' + className) == d)
							|| currentVal == className) {
						currentDate = $(evTr).find(">td input[type='hidden']")
								.next()[0];
						return false;
					}
				} catch (e) {

				}
			});
	return currentDate;
};

/**
 * 获取所有的上级节点
 * 
 * @param data
 */
var findCanOp = function(className) {
	var data = findDataByClsName(className);
	var tempData = [];
	var currentCls = $(data).prev().val();
	$(data).attr("class", "tbdiv");
	tempData.push(data);
	var tr = $(data).parent().parent().prev();
	while (tr.length == 1) {
		try {
			var chiVal = tr.find(">td input[type='hidden']").val();
			if (currentCls.indexOf(chiVal + '.') == 0
					&& 1 == compareCount(chiVal, currentCls)) {
				currentCls = chiVal;
				var currentData = tr.find(">td input[type='hidden']").next();
				currentData.attr("class", "tbdiv");
				tempData.push(currentData[0]);
				// tempData.push(tr);

			}
			tr = tr.prev();
		} catch (e) {
			tr = tr.prev();
		}
	}

	return tempData;
	// alert(tempData.length);
};

/**
 * 倒序打开菜单
 * 
 * @param tempData
 */
var opMenu = function(className) {
	var tempData = findCanOp(className);
	for (var i = tempData.length - 1; i >= 0; i--) {
		openOrCloseMenu(tempData[i]);
	}
};

/**
 * 打开或关闭下级菜单
 * 
 * @param data
 * @returns
 */
var openOrCloseMenu = function(data) {
	var classVal = $(data).attr("class");
	if (classVal == 'tbdiv tdcurrent') {
		// 关闭子菜单
		$(data).attr("class", "tbdiv");
		var parVal = $(data).parent().children('input[type="hidden"]').val();
		/* alert(inp); */
		var par = $(data).parent().parent();
		var nextTr = par.nextAll('tr');
		nextTr.each(function(m, chilNode) {
			var chiVal = $(chilNode).find(">td input[type='hidden']").val();
			if (chiVal.indexOf(parVal) == 0) {
				$(chilNode).find(">td div[class='tbdiv tdcurrent']").attr(
						"class", "tbdiv");
				$(chilNode).hide('slow');
			}
		});
	} else {
		// 打开子菜单
		var parVal = $(data).parent().children('input[type="hidden"]').val();
		/* alert(inp); */
		var par = $(data).parent().parent();
		var nextTr = par.nextAll('tr');
		var flag = 'false';
		nextTr.each(function(m, chilNode) {
			var chiVal = $(chilNode).find(">td input[type='hidden']").val();
			if (chiVal.indexOf(parVal) == 0
					&& 1 == compareCount(parVal, chiVal)) {
				// $(chilNode).display('bolck');
				// $(chilNode).css('display',"block");
				flag = 'true';
				$(chilNode).show('slow');
			}
		});
		if (flag == 'true') {
			$(data).attr("class", "tbdiv tdcurrent");
		}
	}
	// setTrWidth();
};
/**
 * 修改或新增查询模板信息
 * 
 * @data 要修改的模板所在的row
 * 
 */
var add_or_update_template = function(data) {
	$('#os_copy').show("slow");
	var tmpName = "";
	if (data != "") {
//		// 新增查询模板
		$("#option").val("update");
		$("#opRow").val($(data).parent().parent().index());
		tmpName = $(data).parent().parent().find("td input[type='hidden']")
				.val();
	} else {
		$("#option").val("add");
		$("#opRow").val(0);
	}
	var initData = getClassFromServer(tmpName);
	$('#tmp_in').val(tmpName);
	$("#pickList").pickList(initData);

};
/**
 * 关闭遮罩
 * @param id 要关闭的id
 * @param ul ul的id
 */
var closePop = function(id,ul){
	$('#'+id).hide();
	$('#'+ul+' li[class="pop_error"]').remove();
	clearFill();
};

/**
 * 清除所有的填充信息
 */
var clearFill = function(){
	$('#tmp_in').val('');
	$('#pickList').empty();
	$('#alia_in').val('');
	$('#alia_edit_in').val('');
};
/**
 * 
 */
var getClassFromServer = function(templateName) {
	var returnValue = "";
	var path = $('#path').val();
	$.ajax({
		url : path + "/refreshData",
		type : "POST",
		dataType : "json",
		data : {
			"templateName" : encodeURI(templateName),
			"action" : encodeURI('getClasses')
		},
		async : false,
		success : function(retVal) {
			returnValue = retVal;
		},
		error : function() {
			alert("查询错误，请联系管理员！");
		}
	});
	return returnValue;
};

/**
 * 比较str2中某个字母是否比str1中某个字母出现的次数大一
 * 
 * @param str1
 * @param str2
 * @returns {number} 1 大一 0 不大于1
 */
var compareCount = function(str1, str2) {
	var chilCount = str_repeat(str2);
	var parCount = str_repeat(str1);
	if (parCount + 1 == chilCount)
		return 1;
	else
		return 0;
};
/**
 * 统计字符串中某个字母出现的次数
 * 
 * @param str
 * @returns {number}
 */
var str_repeat = function(str) {
	var sub = ".";
	var k = 0, sum = 0;
	k = str.indexOf(sub);
	while (k > -1) {
		sum += 1;
		k = str.indexOf(sub, k + 1);
	}
	return sum;
};

/**
 * 设置窗体高度
 * 
 * 
 */
var setTrWidth = function() {
	var browser = $('#browser').height() + 65;
	if (browser < 600) {
		browser = 600;
	}
	IFrameResizeByHeight(browser + "px");
};

/**
 * 刷新模型视图
 */
function refreshTemplate(classTitle) {
	var path = $('#path').val();
	var returnData = [];
	$.ajax({
		url : path + "/refreshData", // 请求的url地址
		dataType : "json", // 返回格式为json
		async : false,// 请求是否异步，默认为异步，这也是ajax重要特性
		data : {
			"action" : "templateData"
		}, // 参数值
		type : "post", // 请求方式
		beforeSend : function() {
		},
		success : function(data) {
			returnData = data;
			return;
		},
		error : function() {
			alert("刷新查询模板失败，检查后台servlet!");
		}
	});
	return returnData;
};
/**
 * 修改名称
 * 
 * @param data
 * @param opName
 *            修改类型
 *     
 */
var updateName = function(data,opName) {
	//\"template\"  ,alia
	var currentData = $(data);
	var span = currentData.parent().prev();
	var tr = currentData.parent().parent().parent().parent();
	var index = tr.index();
	var tempVal = span.text();
	span.empty();
	span.append('<input  class="inptext" type="text"  value="' + tempVal
			+ '"  onblur="checkVal(this,\'' + tempVal + '\',' + index + ',\''+opName +'\')"/>');
	span.children('input').focus().val(tempVal);
	currentData.parent().empty();
};

/**
 * 同步修改的模板名称
 * 
 * @param data
 *            当前dom对象
 * @param oldTmpName
 *            旧的模板名称
 * @param index
 *            要修改的行
 * @param opName
 *            修改类型
 *            
 */
var checkVal = function(data,oldName,index,opName){
	var oldTmpName = oldName;
	var currentData = $(data).parent();
    var newVal = $(data).val().replace(/(^\s*)|(\s*$)/g, '');
    var tempNewValue = '';
    if  (opName == 'template')
    	tempNewValue =newVal ;
    else{
    	var temp  = $(data).parent().parent().prev().val();
    	tempNewValue = temp.substring(0,temp.lastIndexOf('.')+1)+newVal;
    }
    if(newVal ==''){
    	currentData.text(oldTmpName);
    	currentData.next().html('<a href="javascript:void(0);" class="tbedit"  onclick="updateName(this,\''+opName+'\');event.cancelBubble=true;"></a>');
    }else if (oldTmpName == newVal) {
        // 没有做任何修改
        currentData.html(oldTmpName);
        currentData.next().html('<a href="javascript:void(0);" class="tbedit"  onclick="updateName(this,\''+opName+'\');event.cancelBubble=true;"></a>');
    	
    } else if(isExistVal(index,tempNewValue)){
    	sweetAlert("警告", "已经存在此名称！", "warning");
    	return ;
    }else {
//    	var flag =  updateLinkWide(data,"classDescr");
    	var checkResult = {};
    	if(opName == 'template'){
    		checkResult.action = 'editTemplateName';
    	}else{
    		checkResult.templateName = $(data).parent().parent().prev().val();
//    		alert(checkResult.templateName);
    		checkResult.action = 'editAliaName';
    	}
    	checkResult.oldName = oldTmpName;
    	checkResult.newName = newVal;
		var result = ajaxToServer("refreshData",
				checkResult);
    	if(result.result){
    		currentData.html(newVal);
    		currentData.next().html('<a href="javascript:void(0);" class="tbedit"  onclick="updateName(this,\''+opName+'\');event.cancelBubble=true;"></a>');
    	}else{
    		sweetAlert("错误", "同步至后台错误，请联系管理员！", "error");
    	}
    }
};
/**
 * 检查重复
 */
var isExistVal = function(opRow,templateName){
	var exist = false;
	$('#templateData tr').each(function() {
		try {
			var index = $(this).index();
			if (index == opRow)
				return true;
			
			var tempName = $(this).find('>td input[type="hidden"]').val();
			if (templateName == tempName ) {
				exist = true;
				return false;
			}
		} catch (e) {
			return true;
		}
	});
	return exist;
};
/**
 * 修改别名
 * 
 * @data 要新增的别名所在的row
 * 
 */
var addAlia = function(data) {
	$('.pop_error').remove();
	$('#alia_add').show("slow");
	var fullName =  $(data).parent().parent().find(">td input[type='hidden']").val();
	
	$('#addAlia').on('click',function(){
		$('.pop_error').remove();
		var aliaName = $('#alia_in').val().replace(/(^\s*)|(\s*$)/g, '');
		if(aliaName == ''){
			$('#alia_ul').append('<li class="pop_error">别名不得为空</li>');
			return false;
		}
		
		var dataJson = {};
		dataJson.action = "addAliaName";
		dataJson.fullName = fullName;
		dataJson.aliaName = aliaName;
		var result = ajaxToServer("refreshData",
				dataJson);
		if(result.result){
			window.location.href = "http://"+getSystemPath()+"/jumpDemo";
		}else{
			sweetAlert("警告", result.message, "warming");
		}
	});
	
};
/**
 * 编辑别名
 * @param data 要修改的dom
 * 
 */
var editAlia = function (data){
	$('#alia_edit').show();
	var fullName = $(data).parent().parent().find('> td input[type="hidden"]').val();
	var aliaName = $(data).parent().parent().find('> td div span').eq(2).text();
	$('#alia_edit_in').val(aliaName).attr("disabled",true); 
	var dataJson = {};
	dataJson.action = "getAliaPro";
	dataJson.fullName = fullName;
	var result = ajaxToServer("refreshData",
			dataJson);
	var source_ul = $('#pro_source ul');
	var target_ul = $('#pro_target ul');

	source_ul.empty();
	target_ul.empty();
	
	if(result.result){
		//找到了
		$.each(result.source,function(){
			source_ul.append('<li title="'+this+'"><a href="javascript:void(0)">'+this+'</a></li>');
		});
		
		$.each(result.target,function(){
			target_ul.append('<li title="'+this+'"><a href="javascript:void(0)">'+this+'</a></li>');
			$('#pro_source ul li[title="'+this+'"]').addClass('current');
		});
	}else{
		sweetAlert("警告", result.message, "warming");
	}
	initPickListEvent("pro_source ul li","pro_target ul");
	$('#alia_submit').on('click',function(){
		$('#ed_al_ul li[class="pop_error"]').remove();
		var aliaJson = {'fullName':fullName};
		var proArray = [];
		$('#pro_target ul li').each(function(){
			proArray.push($(this).attr('title'));
		});
		aliaJson.pros = proArray.join(",");
		if(0 == proArray.length){
			$('#ed_al_ul').append('<li class="pop_error">请选择结果显示列</li>');
		}else{
			aliaJson.action = "updatePros";
			var result = ajaxToServer("refreshData",
					aliaJson);
			if (result.result) {
				// 从新加载页面
				window.location.href = "http://"+getSystemPath()+"/jumpDemo";
			} else {
				sweetAlert("错误", result.message, "error");
			}
		}
	});
	$('#close_edit_alia').on('click',function(){
		closePop('alia_edit',"ed_al_ul");
	});	
};
/**
 * 初始化pickList事件
 * @param sourceDir 待选列表id路径
 * @param targetDir 已选列表id路径
 */
var initPickListEvent = function(sourceDir,targetDir){
	$('#'+sourceDir).on('click',function(){
		var curCls = $(this).attr('class');
		if(curCls !='current'){
			var li = $(this).clone();
			li.appendTo($('#'+targetDir));
			li.on('click',function(){
				var tittle = $(this).attr("title");
				$('#'+sourceDir).each(function(i,data){
					var tempTitle = $(data).attr('title');
					if(tittle == tempTitle){
						$(data).removeClass();
						return false;
					}
				});
				$(this).remove();
			});
			$(this).addClass('current');
		}
	});
	
	$('#'+targetDir+' li').on('click',function(){
		var tittle = $(this).attr("title");
		$('#'+sourceDir).each(function(i,data){
			var tempTitle = $(data).attr('title');
			if(tittle == tempTitle){
				$(data).removeClass();
				return false;
			}
		});
		$(this).remove();
	});	
};
/**
 * 删除数据
 */
var deleteData = function(data){
	var deleteData = $(data).parent().parent().find('td input[type="hidden"]').val();
	var tempVal = $(data).parent().parent().find('> td div span').eq(2).text();
	swal({
		title : "删除提示",
		text : '确定要删除"'+tempVal+'"吗？',
		type: "warning",
		showCancelButton: true,   
		confirmButtonColor: "#DD6B55",   
		confirmButtonText: '是的，我要删除',   
		cancelButtonText: '取消',   
		closeOnConfirm: false,   
		closeOnCancel: true
	},
	function(isConfirm) {
		if(isConfirm){
			var data = {'action':'deleteData'};
			data.deleteData = deleteData;
			var resultJs = ajaxToServer("refreshData", data);
			if (resultJs.result)
				window.location.href = "http://"+getSystemPath()+"/jumpDemo";
			else
				sweetAlert("错误", resultJs.message, "error");
		}
	});
};